package com.spzx.report.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.report.aiTools.SpzxAiQuest;
import com.spzx.report.entity.VOrderInfo;
import com.spzx.report.entity.VOrderInfoJSONObject;
import com.spzx.report.mapper.VOrderInfoMapper;
import com.spzx.report.service.SpzxReportService;
import com.spzx.report.vectorTools.PineconeKeyConst;
import com.spzx.report.vectorTools.PineconeSimilaryUtil;
import io.netty.util.internal.SocketUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author dxt
 * @create 2025-06-11-15:33
 */
@Service
public class SpzxReportServiceImpl implements SpzxReportService {

    @Autowired
    private VOrderInfoMapper vOrderInfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Override
    public Map<String, Object> getAiReport(String question) {

        //对话
        // 创建SpzxAiQuest实例，用于处理问题并生成答案
        SpzxAiQuest  spzxAiQuest = new SpzxAiQuest();

        // 使用SpzxAiQuest实例处理问题，返回答案的JSON字符串
        String answerJson = spzxAiQuest.processQuestion(question);

        // 将答案的JSON字符串解析为VOrderInfoJSONObject对象，以便进一步处理
        VOrderInfoJSONObject vOrderInfoJSONObject = JSON.parseObject(answerJson, VOrderInfoJSONObject.class);

        Map<String, Object> aiReportMap = new HashMap<>();

        String answerToken = UUID.randomUUID().toString().replace("-", "");

        redisTemplate.opsForValue().set(answerToken, vOrderInfoJSONObject, 5, TimeUnit.MINUTES);
        aiReportMap.put("answerToken", answerToken);
        aiReportMap.put("countText", vOrderInfoJSONObject.getCountKeyword());
        aiReportMap.put("groupText", vOrderInfoJSONObject.getGroupKeyword());

        return aiReportMap;
    }

    @Override
    public List<Map<String, Object>> getDataReport(String answerToken) {
        VOrderInfoJSONObject vOrderInfoJSONObject = (VOrderInfoJSONObject) redisTemplate.opsForValue().get(answerToken);
        /***
         * 1 用向量数据库匹配相似工具，匹配ai过滤关键词，获得元数据(word和column)，作为后期拼接报表sql的具体字段和条件数据
         */
        VOrderInfoJSONObject vectorData = getVectorData(vOrderInfoJSONObject);

        /***
         * 2 拼接sql语句
         */
        QueryWrapper<VOrderInfo> vOrderInfoQueryWrapper= new QueryWrapper<>();
        vOrderInfoQueryWrapper = getMyReportWrapper(vOrderInfoQueryWrapper,vectorData);
        System.out.println(vOrderInfoQueryWrapper);
        List<Map<String, Object>> maps = vOrderInfoMapper.selectMaps(vOrderInfoQueryWrapper);
        //返回xy轴的集合
        return maps;
    }


    private QueryWrapper<VOrderInfo> getMyReportWrapper(QueryWrapper<VOrderInfo> vOrderInfoQueryWrapper, VOrderInfoJSONObject vectorData) {
        //聚合
        String countKeyword = vectorData.getCountKeyword();
        String countStr = "";
        if(countKeyword.equals("order_amount")){
            countStr = "sum(order_amount) as count";
        }else {
            countStr = "count("+countKeyword+") as count";
        }
        //分组
        String groupKeyword = vectorData.getGroupKeyword();
        String groupStr = "";
        String group = "";
        if(groupKeyword.equals("create_date")){
            group = "DATE_FORMAT( create_date, '%Y-%m-%d' )";
            groupStr = "DATE_FORMAT( create_date, '%Y-%m-%d' ) as groupTag";
        }else {
            group = groupKeyword;
            groupStr = groupKeyword + " as groupTag";
        }

        // 拼接聚合和分组
        vOrderInfoQueryWrapper.select(countStr,groupStr).groupBy(group);

        //条件
        String skuName = vectorData.getSkuName();
        String tmName = vectorData.getTmName();
        String provinceName = vectorData.getProvinceName();
        vOrderInfoQueryWrapper.eq(StringUtils.hasText(skuName),"sku_name",skuName);
        vOrderInfoQueryWrapper.eq(StringUtils.hasText(tmName),"tm_name",tmName);
        vOrderInfoQueryWrapper.eq(StringUtils.hasText(provinceName),"province_name",provinceName);

        return vOrderInfoQueryWrapper;
    }

    private VOrderInfoJSONObject getVectorData(VOrderInfoJSONObject vOrderInfoJSONObject) {

        // 获取去聚合和分组关键词
        String countKeyword = vOrderInfoJSONObject.getCountKeyword();
        String groupKeyword = vOrderInfoJSONObject.getGroupKeyword();

        // 相似性比对
        // 聚合
        // 线程优化
        CompletableFuture<Void> countCompletableFuture = CompletableFuture.runAsync(new Runnable() {
            @Override
            public void run() {
                Map<String, String> countEmbeddings = PineconeSimilaryUtil.getPineconeSimilarityEmbeddings(countKeyword, PineconeKeyConst.PCK);
                String countColumn = countEmbeddings.get("column");
                //  判断聚合字段是否为空 默认为订单金额
                if (StringUtils.isEmpty(countColumn)) {
                    countColumn = "order_amount";
                }
                vOrderInfoJSONObject.setCountKeyword(countColumn);
            }
        }, threadPoolExecutor);

        //分组
        // 线程优化
        CompletableFuture<Void> groupCompletableFuture = CompletableFuture.runAsync(new Runnable() {
            @Override
            public void run() {
                Map<String, String> groupEmbeddings = PineconeSimilaryUtil.getPineconeSimilarityEmbeddings(groupKeyword, PineconeKeyConst.PGK)  ;
                String groupColumn = groupEmbeddings.get("column");
                //  判断分组字段是否为空 默认为下单时间
                if(StringUtils.isEmpty(groupColumn)){
                    groupColumn = "create_date";
                }
                vOrderInfoJSONObject.setGroupKeyword(groupColumn);
            }
        }, threadPoolExecutor);

        //条件
        //  品牌
        // 线程优化
        String tmName = vOrderInfoJSONObject.getTmName();
        CompletableFuture<Void> tmCompletableFuture = CompletableFuture.runAsync(new Runnable() {
            @Override
            public void run() {
                if(StringUtils.hasText(tmName)){
                    String tmWord = PineconeSimilaryUtil.getPineconeSimilarityEmbeddings(tmName, PineconeKeyConst.PSK).get("word");
                    vOrderInfoJSONObject.setTmName(tmWord);
                }
            }
        }, threadPoolExecutor);

        //  商品
        // 线程优化
        String skuName = vOrderInfoJSONObject.getSkuName();
        CompletableFuture<Void> skuCompletableFuture = CompletableFuture.runAsync(new Runnable() {
            @Override
            public void run() {
                if(StringUtils.hasText(skuName)){
                    String skuWord = PineconeSimilaryUtil.getPineconeSimilarityEmbeddings(skuName, PineconeKeyConst.PSK).get("word");
                    vOrderInfoJSONObject.setSkuName(skuWord);
                }
            }
        }, threadPoolExecutor);

        //  城市
        // 线程优化
        String provinceName = vOrderInfoJSONObject.getProvinceName();
        CompletableFuture<Void> provinceCompletableFuture = CompletableFuture.runAsync(new Runnable() {
            @Override
            public void run() {
                if(StringUtils.hasText(provinceName)){
                    String provinceWord = PineconeSimilaryUtil.getPineconeSimilarityEmbeddings(provinceName, PineconeKeyConst.PSK).get("word");
                    vOrderInfoJSONObject.setProvinceName(provinceWord);
                }
            }
        }, threadPoolExecutor);

        CompletableFuture.allOf(countCompletableFuture,groupCompletableFuture,tmCompletableFuture,skuCompletableFuture,provinceCompletableFuture).join();

        return vOrderInfoJSONObject;
    }
}
